package com.think.teaching.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.think.common.controller.BaseController;
import com.think.common.model.Result;
import com.think.common.model.ResultCode;
import com.think.common.utils.Common;
import com.think.teaching.model.Chapter;
import com.think.teaching.model.Course;
import com.think.teaching.model.CourseHistory;
import com.think.teaching.service.impl.ChapterServiceImpl;
import com.think.teaching.service.impl.CourseHistoryService;
import com.think.teaching.service.impl.CourseServiceImpl;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/v1")
@Api(tags =  "课程记录接口文档")
public class CourseHistoryController extends BaseController {
	
	@Autowired
	private CourseHistoryService courseHistoryService;
	@Autowired
	private ChapterServiceImpl chapterServiceImpl;
	@Autowired
	private CourseServiceImpl courseServiceImpl;
	
	@PostMapping("open/courseHistory")
	public Result StatHistory(@RequestBody()CourseHistory data) {
		data.CheckObjectComplete();
		if (Common.GetCurrentAuthor()!=null) {
			data.setCreatedBy(Common.GetCurrentAuthor().getUserId());
		}
		else {
			data.setCreatedBy(-1);
		}
		Course course = courseServiceImpl.getById(data.getCourseId());
		if (course == null) {
			return Result.failure(ResultCode.COURSE_NOT_EXIST);
		}
		if (data.getChapterId()>0) {
			Chapter chapter = chapterServiceImpl.getById(data.getChapterId());
			if (chapter == null) {
				return Result.failure(ResultCode.CHAPTER_NOT_EXIST);
			}
			if (chapter.getCourseId()!= data.getCourseId()) {
				return Result.failure(ResultCode.CHAPTER_MISSMATCH_COURSE);
			}
		}
		courseHistoryService.AddObjectEntity(data);
		return Result.success(data);
	}
	
	@GetMapping("open/courseHistories/{page}/{count}")
	public Result ListHistorys(@PathVariable("page")Integer page,@PathVariable("count")Integer count,@RequestParam(defaultValue = "-1",required = false)Integer courseId) {
		
		return Result.success(courseHistoryService.ListHistorys(page, count, courseId));
	}
}
